#!/usr/bin/env python
# Settings

###########################################################################
# 
#  Copyright (C) 2007 Sarath Lakshman. All rights reserved.
# 
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################

import sys,shelve
from PyQt4 import QtGui,QtCore

class settings(QtGui.QDialog):

	def __init__(self,ent_no):
		QtGui.QDialog.__init__(self)
			
		self.setWindowIcon(QtGui.QIcon("pics/logo.png"))

		self.setWindowTitle("Database Settings")

		self.database=shelve.open('settings','c')['DB'] # grab current database path
			
		self.db=shelve.open(self.database,'c')

		self.ent_no=ent_no
			
		self.gbox=QtGui.QGroupBox("Database")
		self.sbox=QtGui.QGroupBox("School")

		self.cur_dbase_name=QtGui.QLabel("Current database : <b>%s</b>" %self.db['DB_NAME'])
			
		self.setname_db=QtGui.QPushButton("Set Database Name")

		self.load_db=QtGui.QPushButton("Load Database")
			
		self.save_db=QtGui.QPushButton("Backup Database")
			
		self.clear_db=QtGui.QPushButton("Clear Database")

		self.connect(self.load_db,QtCore.SIGNAL('clicked()'),self.fileOpen)
		self.connect(self.setname_db,QtCore.SIGNAL('clicked()'),self.inputdbName)
		self.connect(self.save_db,QtCore.SIGNAL('clicked()'),self.fileSave)

		self.cur_school_name=QtGui.QLabel("School Name : <b>%s</b>" %shelve.open('settings','c')['schoolname'])
		self.school_db=QtGui.QPushButton("Set school")

		vs_layout=QtGui.QVBoxLayout()
		vs_layout.addWidget(self.cur_school_name)
		vs_layout.addWidget(self.school_db)
		self.sbox.setLayout(vs_layout)
		self.connect(self.school_db,QtCore.SIGNAL('clicked()'),self.inputschoolName)
		self.connect(self.clear_db,QtCore.SIGNAL('clicked()'),self.cleardb)


		vlayout=QtGui.QVBoxLayout()
		hlayout1=QtGui.QHBoxLayout()
		hlayout2=QtGui.QHBoxLayout()
		hlayout3=QtGui.QHBoxLayout()
		hlayout4=QtGui.QHBoxLayout()

		vlayout.addWidget(self.cur_dbase_name)
		hlayout1.addWidget(self.setname_db)
		hlayout1.addWidget(self.load_db)
		hlayout2.addWidget(self.save_db)
		hlayout2.addWidget(self.clear_db)
		vlayout.addLayout(hlayout1)
		vlayout.addLayout(hlayout2)
		self.gbox.setLayout(vlayout)
		hlayout4.addWidget(self.gbox)
		Vlayout=QtGui.QVBoxLayout()
		Vlayout.addLayout(hlayout4)
		Vlayout.addWidget(self.sbox)
		self.setLayout(Vlayout)


	def fileOpen( self ):
		fn = QtGui.QFileDialog.getOpenFileName(self, "Choose the database" , ""," (*.admdb)")
		if not fn.isEmpty():
			self.filename = fn
			shelve.open('settings','c')['DB']=str(self.filename)
			self.cur_dbase_name.setText("Current database : <b>%s</b>" %shelve.open(shelve.open('settings','c')['DB'],'c')['DB_NAME'])
			self.ent_no[0]=1
			
			
	def fileSave( self ):
       		fn = QtGui.QFileDialog.getSaveFileName(self, "Save database" , ""," (*.admdb)")
        	if not fn.isEmpty():
        		self.filename = fn
        	    	
			filestream=open(self.database,'rb').read()
			fout=open(str(self.filename).replace('.admdb', "")+'.admdb','wb')
			fout.write(filestream)
			fout.close()
		



	def inputdbName( self ):
		
		name=QtGui.QInputDialog.getText(self, "", "Database Name:", QtGui.QLineEdit.Normal);
		
		if not (str(name[0]).isspace() or str(name[0])==""):
			
        		self.db['DB_NAME']=str(name[0])

			self.cur_dbase_name.setText("Current database : <b>%s</b>"%str(name[0]))


	def inputschoolName( self ):
		
		name=QtGui.QInputDialog.getText(self, "", "Database Name:", QtGui.QLineEdit.Normal);
		
		if not (str(name[0]).isspace() or str(name[0])==""):
			
        		shelve.open('settings','c')['schoolname']=str(name[0])
			self.cur_school_name.setText("School Name : <b>%s</b>" %shelve.open('settings','c')['schoolname'])


	def cleardb( self ):
		reply=QtGui.QMessageBox.question(self,"Confirmation", "Do you really want to clear whole database ?. It will cause deletion of all entries.",QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
		if reply==QtGui.QMessageBox.Yes:
			tmp=self.db['DB_NAME']
			shelve.open('settings','c')['DB']='database'
			self.db=shelve.open('database','c')
			self.db.clear()
			self.db['DB_NAME']=tmp
			#shelve.open('database','c')['0']=1
			self.inputdbName()




	def do_password_check( self ):
		self.gbox.setEnabled(False)
		self.sbox.setEnabled(False)

		input_txt=QtGui.QInputDialog.getText(self, " ", "Enter Administration Password ", QtGui.QLineEdit.Normal);
		
		if not (str(input_txt[0]).isspace() or str(input_txt[0])==""):	
        		if str(input_txt[0])=='//admin@school//':
				self.gbox.setEnabled(True)
				self.sbox.setEnabled(True)
		else:
			reply=QtGui.QMessageBox.warning(self,"Wrong password" ,"Incorrect administration password !")

if __name__=='__main__':

	app=QtGui.QApplication([])
	w=settings()
	w.show()

	sys.exit(app.exec_())
